package com.lhczf.lucenedb.threads;

import com.lhczf.lucenedb.service.DataHub;
import com.lhczf.lucenedb.util.FileUtils;
import com.lhczf.lucenedb.util.SpringUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;

@Slf4j
public class ProducerTread extends Thread {

    private File dataDir;

    public ProducerTread(String name, File dataDir) {
        super(name);
        this.dataDir = dataDir;
    }

    @Override
    public void run() {
        //启动之前先处理当前文件夹下未处理的文件
        FileUtils.dealOldFiles(dataDir);
        final Path path = Paths.get(dataDir.getAbsolutePath());
        try (WatchService watchService = FileSystems.getDefault().newWatchService()) {
            Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                    log.info("启动成功，监听目录为：{}", dir.toAbsolutePath());
                    dir.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);
                    return FileVisitResult.CONTINUE;
                }
            });
            while (true) {
                boolean flag = reciveFileInfo(watchService);
                if (!flag) {
                    log.warn("文件监控返回false,退出监控。");
                    break;
                }
            }
        } catch (IOException e) {
            log.error("启动数据文件监控过程中出现异常。", e);
        }
    }

    private boolean reciveFileInfo(WatchService watchService) {
        boolean result = false;
        try {
            WatchKey key = watchService.take();
            for (WatchEvent<?> watchEvent : key.pollEvents()) {
                final WatchEvent<Path> watchEventPath = (WatchEvent<Path>) watchEvent;
                Path path = (Path) key.watchable();
                final Path filename = watchEventPath.context();
                DataHub.dataQueue.put(path + File.separator + filename.toString());
            }
            result = key.reset();
        } catch (InterruptedException e) {
            log.error("", e);
            Thread.currentThread().interrupt();
        }
        return result;
    }
}
